<?php

class Silk_Mapi_Model_Quote_Item extends Mage_Sales_Model_Quote_Item
{
	/**
     * Check product representation in item
     *
     * @param   Mage_Catalog_Model_Product $product
     * @return  bool
     */
    public function representProduct($product)
    {
        $itemProduct = $this->getProduct();
        if (!$product || $itemProduct->getId() != $product->getId()) {
            return false;
        }


        /**
         * Check maybe product is planned to be a child of some quote item - in this case we limit search
         * only within same parent item
         */
        $stickWithinParent = $product->getStickWithinParent();
        if ($stickWithinParent) {
            if ($this->getParentItem() !== $stickWithinParent) {
                throw new Exception("ee1");
                return false;
            }
        }
        //throw new Exception("e2");
        // Check options
        $itemOptions = $this->getOptionsByCode();
        $productOptions = $product->getCustomOptions();

        if (!$this->compareOptions($itemOptions, $productOptions)) {
            return false;
        }
        if (!$this->compareOptions($productOptions, $itemOptions)) {
            return false;
        }
        //throw new Exception("e3");
        //Check is Gift
        $giftProductId = Mage::registry("gift_product_id");
        if($giftProductId == $product->getId())
        {
            $giftId = Mage::registry("gift_id");
            if(!$this->getGiftId()) return false;
            if($this->getGiftId() != $giftId)
            {
                return false;
            }
        }

        if($this->getGiftId())
        {
            if($giftProductId != $product->getId())
            {
                return false;
            }
        }
        //throw new Exception("e4");
        //Check exchange product
        if($product->getUsePoint())
        {
            $session = Mage::getSingleton('checkout/session');

            if (
                ($session->getExchange() == $this->getProductId() && $this->getExchange())
                || (!$this->getExchange() && !$session->getExchange())
            ) {
                return true;
            } else {
                return false;
            }

        }
        //throw new Exception("e5");
        //Check Gift Product
        
        return true;
    }
}
